package com.dai.spec.gxk.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dai.spec.common.constant.AvatarUrlConstants;
import com.dai.spec.common.constant.RoleConstants;
import com.dai.spec.common.core.domain.entity.SysUser;
import com.dai.spec.common.exception.base.BaseException;
import com.dai.spec.common.utils.SecurityUtils;
import com.dai.spec.common.utils.StringUtils;
import com.dai.spec.gxk.domain.Teacher;
import com.dai.spec.gxk.mapper.TeacherMapper;
import com.dai.spec.gxk.service.TeacherService;
import com.dai.spec.system.service.ISysUserService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 教师信息管理Service业务层处理
 *
 * @author daikl
 * @date 2024-02-29
 */
@Service
public class TeacherServiceImpl extends ServiceImpl<TeacherMapper, Teacher> implements TeacherService {
    private TeacherMapper teacherMapper;

    private ISysUserService iSysUserService;

    public TeacherServiceImpl(TeacherMapper teacherMapper, ISysUserService iSysUserService) {
        this.teacherMapper = teacherMapper;
        this.iSysUserService = iSysUserService;
    }

    /**
     * 根据教师姓名查询teacherId
     * @param name 教师姓名
     * @return
     */
    @Override
    public Long getByName(String name) {
        Long teacherId = teacherMapper.getByName(name);
        return teacherId;
    }

    /**
     * 查询教师信息管理列表
     *
     * @param teacher 教师信息管理
     * @return 教师信息管理
     */
    @Override
    public List<Teacher> queryList(Teacher teacher) {
        LambdaQueryWrapper<Teacher> queryWrapper = new LambdaQueryWrapper<>();
        if (StringUtils.isNotEmpty(teacher.getJobNumber())) {
            queryWrapper.eq(Teacher::getJobNumber, teacher.getJobNumber());
        }
        if (StringUtils.isNotEmpty(teacher.getName())) {
            queryWrapper.like(Teacher::getName, teacher.getName());
        }
        if (StringUtils.isNotEmpty(teacher.getProfessionalTitle())) {
            queryWrapper.eq(Teacher::getProfessionalTitle, teacher.getProfessionalTitle());
        }
        return this.list(queryWrapper);
    }
    /**
     * 新增教师，添加用户及权限
     * @param teacher
     * @return
     */
    @Override
    @Transactional
    public int saveWithUser(Teacher teacher) {
        //工号、性别、姓名、手机号码
        this.validateTeacher(teacher);
        SysUser sysUser = this.buildSysUser(teacher);
        int rows = iSysUserService.insertUser(sysUser);
        Long userId = sysUser.getUserId();
        teacher.setUserId(userId);
        teacherMapper.insert(teacher);
        return rows;
    }
    /**
     * 修改教师
     * @param teacher
     * @return
     */
    @Override
    @Transactional
    public int updateWithUser(Teacher teacher) {
        this.validateTeacher(teacher);
        Long userId = teacher.getUserId();
        this.checkUserId(userId);
        SysUser sysUser = iSysUserService.selectUserById(userId);
        this.buildUpdateSysUser(teacher, sysUser);
        int rows = iSysUserService.updateUser(sysUser);
        teacherMapper.updateById(teacher);
        return rows;
    }
    /**
     * 删除/批量删除教师
     * @param ids
     * @return
     */
    @Override
    @Transactional
    public int removeByIdsWithUser(List<Long> ids) {
        if (StringUtils.isEmpty(ids)){
            throw new BaseException("ids为空！");
        }
        ArrayList<Long> userIds = new ArrayList<>();
        for (Long id : ids) {
            LambdaQueryWrapper<Teacher> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(Teacher::getId,id);
            Teacher teacher = teacherMapper.selectOne(queryWrapper);
            String jobNumber = teacher.getJobNumber();
            SysUser sysUser = iSysUserService.selectUserByUserName(jobNumber);
            userIds.add(sysUser.getUserId());
        }
        Long[] idsArray = toIdsArray(userIds);
        int rows = iSysUserService.deleteUserByIds(idsArray);
        teacherMapper.deleteBatchIds(ids);
        return rows;
    }

    private static Long[] toIdsArray(List<Long> ids) {
        Long[] userIds = new Long[ids.size()];
        for (int i = 0; i < ids.size(); i++) {
            userIds[i] = ids.get(i);
        }
        return userIds;
    }
    private static void buildUpdateSysUser(Teacher teacher, SysUser sysUser) {
        String jobNumber = teacher.getJobNumber();
        String teacherName = teacher.getName();
        String phoneNumber = teacher.getPhoneNumber();
        String sex = teacher.getSex();
        sysUser.setUserName(jobNumber);
        sysUser.setNickName(teacherName);
        sysUser.setPhonenumber(phoneNumber);
        sysUser.setSex(sex);
    }

    /**
     * 封装sysUser对象
     * @param teacher
     */
    private static SysUser buildSysUser(Teacher teacher) {
        String jobNumber = teacher.getJobNumber();
        String teacherName = teacher.getName();
        String phoneNumber = teacher.getPhoneNumber();
        String sex = teacher.getSex();
        SysUser sysUser = new SysUser();
        //默认教师工号作为登录时的用户名
        sysUser.setUserName(jobNumber);
        //默认初始密码为工号
        String encryptPassword = SecurityUtils.encryptPassword(jobNumber);
        sysUser.setPassword(encryptPassword);
        sysUser.setNickName(teacherName);
        sysUser.setPhonenumber(phoneNumber);
        sysUser.setSex(sex);
        //根据性别设置默认头像
        if ("0".equals(sex)) {
            sysUser.setAvatar(AvatarUrlConstants.TEACHER_MAN_AVATAR);
        } else if ("1".equals(sex)) {
            sysUser.setAvatar(AvatarUrlConstants.STUDENT_MAN_AVATAR);
        }
        //设置权限
        sysUser.setRoleId(RoleConstants.TEACHER);
        sysUser.setRoleIds(Arrays.asList(RoleConstants.TEACHER).toArray(new Long[0]));

        return sysUser;
    }

    /**
     * 教师字段校验
     * @param teacher
     */
    private static void validateTeacher(Teacher teacher) {
        if (StringUtils.isEmpty(teacher.getJobNumber())){
            throw new BaseException("教师工号不能为空！");
        }
        if (StringUtils.isEmpty(teacher.getSex())){
            throw new BaseException("教师性别不能为空！");
        }
        if (StringUtils.isEmpty(teacher.getName())){
          throw new BaseException("教师姓名不能为空！");
        }
        if (StringUtils.isEmpty(teacher.getPhoneNumber())){
            throw new BaseException("教师电话号码不能为空！");
        }
    }

    private static void checkUserId(Long userId) {
        if (null == userId){
            throw new BaseException("userId不能为空，该教师没有关联用户表！");
        }
    }


}
